package com.sdkj.dspservice.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sdkj.dspservice.common.base.service.impl.CrudServiceImpl;
import com.sdkj.dspservice.common.utils.RedisUtils;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.common.utils.UserUtils;
import com.sdkj.dspservice.modules.sys.dao.RoleDao;
import com.sdkj.dspservice.modules.sys.dao.UserDao;
import com.sdkj.dspservice.modules.sys.dao.UserRoleDao;
import com.sdkj.dspservice.modules.sys.entity.Role;
import com.sdkj.dspservice.modules.sys.entity.User;
import com.sdkj.dspservice.modules.sys.entity.UserRole;
import com.sdkj.dspservice.modules.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单表service实现类
 *
 * @author tm
 * @version 2020/11/23 18:09
 */
@Service
@Transactional(readOnly = true)
public class UserServiceImpl extends CrudServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional(readOnly = false)
    @Override
    public boolean saveOrUpdate(User user) {
        // 记录是否为插入
        boolean isNewRecord = user.isNewRecord();
        if(isNewRecord){
            // 密码加密
            user.setPassword(UserUtils.passwordEncrypt(user.getPassword()));
        }else {
            // 更新操作
            // 如果有新密码，则该为新密码
            if(StringUtils.isNotBlank(user.getNewPassword())){
                user.setPassword(UserUtils.passwordEncrypt(user.getNewPassword()));
            }
        }
        // 执行save
        boolean result = super.saveOrUpdate(user);
        // 角色列表不为空，则进行用户角色关联
        if(!user.getRoleList().isEmpty()){
            // 删除原用户角色关联
            userRoleDao.deleteByUserId(user.getId());
            // 添加用户角色关联
            for(Role role : user.getRoleList()){
                UserRole userRole = new UserRole(user.getId(), role.getId());
                userRoleDao.insert(userRole);
            }
        }
        return result;
    }

    public void remove(User user) {
        super.removeById(user.getId());
        // 删除时，清除用户关联
        userRoleDao.deleteByUserId(user.getId());
    }

    @Override
    public Integer getCountByLoginName(String loginName) {
        return dao.getCountByLoginName(loginName);
    }

    @Override
    public User getByLoginName(String loginName) {
        RedisUtils redisUtils = new RedisUtils(redisTemplate);
        // 先从redis查询
        User user = (User) redisUtils.getObject(RedisUtils.LOGIN_MODULE, loginName);
        // redis不存在，则从数据库查询
        if(user == null){
            user = dao.getByLoginName(loginName);
            redisUtils.setObject(RedisUtils.LOGIN_MODULE, loginName, user);
        }
        return user;
    }

    @Override
    public User getByCdpUserId(String cdpUserId) {
        return dao.getByCdpUserId(cdpUserId);
    }

    @Override
    public List<User> listByRoleId(String roleId) {
        return dao.findListByRoleId(roleId);
    }

    /**
     * 跟角色英文名获取用户ID列表
     * @param enName
     * @return
     */
    @Override
    public List<String> listIdByRoleEnName(String enName) {
        List<String> userIdList = new ArrayList<>();
        // 根据角色英文名获取角色id
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("en_name", enName);
        Role role = roleDao.selectOne(roleQueryWrapper);
        if(role != null){
            // 获取该角色的关联用户id
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("role_id", role.getId());
            List<UserRole> userRoleList = userRoleDao.selectList(userRoleQueryWrapper);
            if(!userRoleList.isEmpty()){
                userIdList = userRoleList.stream().map(UserRole::getUserId).collect(Collectors.toList());
            }
        }
        return userIdList;
    }

    /**
     * 跟角色英文名获取用户列表
     * @param enName
     * @return
     */
    @Override
    public List<User> listByRoleEnName(String enName) {
        List<User> userList = new ArrayList<>();
        // 获取用户ID列表
        List<String> userIdList = listIdByRoleEnName(enName);
        // 获取用户列表
        if(!userIdList.isEmpty()){
            userList = dao.selectBatchIds(userIdList);
        }
        return userList;
    }

    @Override
    public IPage<User> pageLink(IPage<User> page, QueryWrapper<User> userQueryWrapper) {
        return dao.pageLink(page, userQueryWrapper);
    }
}
